<?php
namespace app\model;

use think\Model;
use app\model\User;

/**
 * 开源项目评价
 */
class ProjectComment extends Model
{
    protected $table = "ea_project_comment";

    /**
     * [setWhere 过来条件]
     * @param [type] $data [description]
     */
    public static function setWhere($data)
    {
        $model = self::whereNull('delete_time');

        # 开源项目ID
        if(isset($data['project_id']) && $data['project_id']){
            $model = $model->where('project_id', $data['project_id']);
        }

        # 是否只查询父类为0的情况
        if(isset($data['parent_id'])){
            $model = $model->where('parent_id', $data['parent_id']);
        }


        return $model;
    }

    /**
     * [getProjectCommentList 获取列表]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function getProjectCommentList($data)
    {
        $list = self::setWhere($data)
            ->field('id, msg, parent_id, project_id, create_time, user_id')
            ->order('create_time DESC')
            ->with([
                # 关联评论人
                'user' => function($query){
                    $query->field('id, nickname, avatar');
                },

                # 是否有子评论内容
                'somCommentList' => function($query) use ($data){
                    $query->field('id, msg, parent_id, project_id, create_time, user_id')->order('id DESC')
                        ->with([
                            # 提交回复评论人的信息
                            'user' => function($query){
                                $query->field('id, nickname, avatar');
                            }
                        ]);
                }
            ])
            ->page($data['page'], 10)
            ->select();

        return $list;
    }

    /**
     * [user 关联评论人信息]
     * @return [type] [description]
     */
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    /**
     * [comment_list 是否有子评论]
     * @return [type] [description]
     */
    public function somCommentList()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }
}